package com.zkingsoft.wechat.pay;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;

import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.web.BaseAction;
import com.zkingsoft.bean.BizActivities;
import com.zkingsoft.bean.BizCollage;
import com.zkingsoft.bean.BizMyCoupon;
import com.zkingsoft.bean.BizOrder;
import com.zkingsoft.bean.BizUser;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.dao.BizCollageInfoDao;
import com.zkingsoft.externalInterface.protocol.paramProtocol.BrandWCPayRequestData;
import com.zkingsoft.externalInterface.weixinUtil.WeixinServiceUtil;
import com.zkingsoft.redis.RedisUserLoginUtils;
import com.zkingsoft.service.BizActivitiesService;
import com.zkingsoft.service.BizCollageDetailService;
import com.zkingsoft.service.BizCollageInfoService;
import com.zkingsoft.service.BizMyCouponService;
import com.zkingsoft.service.BizOrderService;
import com.zkingsoft.tools.WxUtils;

/**
 * @description (支付表)
 * @author 何明
 * @date 2018-05-23 00:08
 */
@Controller
@RequestMapping(value = "wxapi/pay")
public class WxPayAction extends BaseAction {

	@Autowired
	private WeixinServiceUtil weixinServiceUtil;
	@Autowired
	private BizCollageDetailService bizCollageDetailService;
	@Autowired
	RedisUserLoginUtils redisUserLoginUtils;
	@Autowired
	private BizMyCouponService bizMyCouponService;
	@Autowired
	private BizActivitiesService activitiesService;
	@Autowired
	private BizOrderService bizOrderService;
	@Autowired
	private BizCollageInfoService bizCollageInfoService;
	@Autowired
	private BizCollageInfoDao bizCollageInfoDao;

	/**
	 * 我要开团（创建预支付）
	 * 
	 * @author HEMING
	 * @email 910000889@qq.com
	 * @date 2018年6月5日
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/createCollage")
	public @ResponseBody AjaxResult createCollage(@RequestBody BizOrder bizOrder) throws HttpException, IOException {
		if (bizOrder == null || bizOrder.getActId() == null || bizOrder.getOrderType() == null) {
			return new AjaxResult(AjaxResult.STATUS_FAIL, AppConstance.PARAMETER_NOT_FULL);
		}
		// 获取登录用户
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		LogUtil.debug("{}#createCollage开始", bizOrder);
		// 将订单信息存入备注
		bizOrder.setOrderRemark(JSONObject.toJSONString(bizOrder));

		// 查询活动标题。价格。图片
		BizActivities act = activitiesService.queryById(bizOrder.getActId());
		if (act == null) {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "获取活动详情错误");
		}
		LogUtil.debug("活动信息：{}", act);
		BizCollage coll = act.getCollage();
		bizOrder.setUpdateBy(loginUser.getOpenId());
		bizOrder.setUserId(loginUser.getOpenId());
		bizOrder.setProductTitle(act.getActTitle());// 活动标题
		bizOrder.setProductImage(act.getActMainText());// 图片
		bizOrder.setOrderType(AppConstance.ACTIVITIES_COLLAGE);
		bizOrder.setOrderStatus(AppConstance.ORDER_STATUS_NOR);
		bizOrder.setPayStatus(AppConstance.PAY_STATUS_DZF);// 待支付
		String price = WxUtils.getCollagePrice(coll.getColProgramme(), bizOrder.getCinfoType());
		LogUtil.debug("拼团价格：{}", price);
		if (StringUtils.isBlank(price)) {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "参数错误");
		}
		BigDecimal collPrice = new BigDecimal(price);// 拼团价
		bizOrder.setProductPrice(collPrice);// 拼团价
		BigDecimal payMoney = collPrice;
		// 如果是团长减去团长优惠金额
		if (bizOrder.getCinfoId() != null && coll.getColHeadRefmoney() != null
				&& coll.getColHeadRefmoney().doubleValue() > 0) {
			payMoney = payMoney.subtract(coll.getColHeadRefmoney());
			LogUtil.debug("团长优惠金额信息：{}", coll.getColHeadRefmoney());
		}
		// 查询优惠券
		if (bizOrder.getCouId() != null) {
			BizMyCoupon bizMyCoupon = bizMyCouponService.findByMcouId(bizOrder.getCouId(), loginUser.getOpenId());
			LogUtil.debug("优惠券信息：{}", bizMyCoupon);
			// 减去优惠券金额
			if (bizMyCoupon != null && bizMyCoupon.getCouValue() != null
					&& bizMyCoupon.getCouValue().doubleValue() > 0) {
				payMoney = payMoney.subtract(bizMyCoupon.getCouValue());
			}
		}
		bizOrder.setPayMoney(payMoney);// 支付金额
		// coll.getColHeadRefother();//团长其它优惠
		// coll.getColProgramme();//拼团方案json

		// 支付金额转分
		payMoney = payMoney.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP);
		LogUtil.debug("支付信息:{}", bizOrder);
		// String desc,String outTradeNo, int price 单位是分, String openId,String
		// attach
		try {
			bizOrder.setCreateBy(loginUser.getUserId());
			bizOrder.setOrderId(UUIDUtil.getRandomID());
			bizOrder.setOrderNo(WxUtils.getOrderNum());// 生成订单号
			//payMoney.intValue()
			BrandWCPayRequestData payData = weixinServiceUtil.createOrder("开团付款", bizOrder.getOrderNo(),
					1, loginUser.getOpenId(), bizOrder.getOrderId());
			if (payData != null) {
				bizOrderService.add(bizOrder);
				LogUtil.debug("开团创建预支付成功！#订单编号：{}", bizOrder.getOrderNo());
				AjaxResult result = new AjaxResult(AjaxResult.STATUS_SUCCESS, Arrays.asList(payData));
				result.putInMap("orderId", bizOrder.getOrderId());
				return result;
			} else {
				LogUtil.error("创建购买VIP预支付订单异常:预支付返回参数为空");
				throw new GlobleException("创建订单失败，请稍后再试");
			}

		} catch (Exception e) {
			LogUtil.error("开团创建预支付异常:{}", e, bizOrder);
			throw new GlobleException("创建订单失败，请稍后再试");
		}
	}

	/**
	 * 查询订单支付结果
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年9月8日
	 * @param orderId
	 * @return
	 * @throws InterruptedException
	 */
	@RequestMapping(value = "/findOrderPayStatus/{orderId}")
	public @ResponseBody AjaxResult findOrderPayStatus(@PathVariable String orderId) throws InterruptedException {
		AjaxResult result = new AjaxResult(AjaxResult.STATUS_SUCCESS, "");
		result.putInMap("status", "err");
		result.putInMap("msg", "查询支付信息失败，请联系客服或者刷新支付信息（错误码:005）");

		BizOrder order = bizOrderService.findById(orderId);
		if (order.getPayStatus().equals(AppConstance.PAY_STATUS_SUC)) {
			result.putInMap("status", "success");
			result.putInMap("msg", "支付成功");

		} else if (order.getPayStatus().equals(AppConstance.PAY_STATUS_FAIL)) {
			result.putInMap("status", "err");
			result.putInMap("msg", "查询支付信息失败，请联系客服或者刷新支付信息（错误码:006）");
		} else {

			LogUtil.debug("订单等待支付中={}。。。", orderId);
			PayThreadPool.waitThread(orderId, new Object());
			result = PayThreadPool.getThreadResult(orderId);
			LogUtil.debug("订单支付完成={}。。。", orderId);
		}
		return result;
	}

}